import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        cartItem: {},
        allState: false
    },
    mutations: {
        resetCartItem(state,nv){
            state.cartItem = nv;
        },
        setCartItem(state, nv) {
            if (state.cartItem[nv.tradeItemId]) {
                state.cartItem[nv.tradeItemId].count += 1;
            } else {
                //给新添加的属性，提供数据监控
                Vue.set(state.cartItem, nv.tradeItemId, nv);
                Vue.set(state.cartItem[nv.tradeItemId], "count", 1);
                Vue.set(state.cartItem[nv.tradeItemId], "status", false);
            }
        },
        addCartCount(state, key) {
            state.cartItem[key].count += 1;
        },
        minusCartCount(state, key) {
            if (state.cartItem[key].count == 0) {
                return;
            }
            state.cartItem[key].count -= 1;
        },
        changeStatus(state, key) {
            let arrs = Object.values(state.cartItem);
            if (key) {
                state.cartItem[key].status = !state.cartItem[key].status;
                // allState先设为true,由对象的长度来判断有没有物品
                state.allState = (arrs.length > 0);
                arrs.forEach((value) => {
                    //只要有一个为假，allState就判为false
                    if (!value.status) {
                        state.allState = false;
                        return;
                    }
                });
            } else {
                state.allState = (arrs.length > 0);
                arrs.forEach((value) => {
                    if (!value.status) {
                        state.allState = false;
                        return;
                    }
                });
            }
        },
        changeAllState(state) {
            state.allState = !state.allState;
            let arrs = Object.values(state.cartItem);
            arrs.forEach((value) => {
                value.status = state.allState;
            });
        },
        removeItem(state, nv) {
            //nv为1是批量删除
            if (nv == 1) {
                let arrs = Object.keys(state.cartItem);
                arrs.forEach((value) => {
                    if (state.cartItem[value].status) {
                        Vue.delete(state.cartItem, value);
                    }
                });
                //只删除一个物品
            } else {
                if (state.cartItem[nv].status) {
                    Vue.delete(state.cartItem, nv);
                }
            }
            this.commit("changeStatus");
        }
    },
    actions: {
    },
    modules: {
    }
})
